import { ConfigEnv, defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "node:path";
import { fileURLToPath, URL } from "node:url";

import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { NaiveUiResolver } from "unplugin-vue-components/resolvers";
import terser from "@rollup/plugin-terser";
import { codecovVitePlugin } from "@codecov/vite-plugin";
import { viteMockServe } from "vite-plugin-mock";
const host = process.env.TAURI_DEV_HOST;
import postCssPxToRem from "postcss-pxtorem";
import autoprefixer from "autoprefixer";
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }: ConfigEnv) => {
  const config = loadEnv(mode, process.cwd());
  const isBuild = command === "build";
  const prodMock = true;
  return {
    plugins: [
      vue(),

      AutoImport({
        imports: [
          "vue",
          {
            "naive-ui": [
              "useDialog",
              "useMessage",
              "useNotification",
              "useLoadingBar",
            ],
          },
        ],
      }),
      Components({
        resolvers: [NaiveUiResolver()],
      }),
      /** 代码覆盖率插件 */
      codecovVitePlugin({
        enableBundleAnalysis: process.env.CODECOV_TOKEN !== undefined,
        bundleName: "hula",
        uploadToken: process.env.CODECOV_TOKEN,
      }),
      /** 压缩代码 */
      terser({
        format: {
          comments: false, // 移除所有注释
        },
        compress: {
          drop_console: true, // 移除 console.log
          drop_debugger: true, // 移除 debugger
        },
      }),
      viteMockServe({
        enable: true,
        logger: false,
        mockPath: "src/mock",
      }),
    ],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        "@comp": resolve(__dirname, "./src/components"),
        "@views": resolve(__dirname, "./src/views"),
        "@utils": resolve(__dirname, "./src/utils"),
        "@enums": resolve(__dirname, "./src/enums"),
        "@stores": resolve(__dirname, "./src/stores"),
        "@api": resolve(__dirname, "./src/api"),
      },
      extensions: [
        ".mjs",
        ".js",
        ".ts",
        ".jsx",
        ".tsx",
        ".json",
        ".vue",
        ".css",
      ],
    },
    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            // 自适应，px>rem转换
            rootValue: 16, // 1rem的大小
            propList: ["*"], // 需要转换的属性，这里选择全部都进行转换
          }),
          autoprefixer({
            // 自动添加前缀
            overrideBrowserslist: [
              "Android 4.1",
              "iOS 7.1",
              "Chrome > 31",
              "ff > 31",
              "ie >= 8",
              //'last 2 versions', // 所有主流浏览器最近2个版本
            ],
            grid: true,
          }),
        ],
      },
    },
    build: {
      target: "esnext",
      cssCodeSplit: true, // 启用 CSS 代码拆分
      minify: "terser", // 指定使用哪种混淆器
      // chunk 大小警告的限制(kb)
      chunkSizeWarningLimit: 1200,
      // 关闭生成map文件 可以达到缩小打包体积
      sourcemap: false,
      // 分包配置
      rollupOptions: {
        output: {
          chunkFileNames: "static/js/[name]-[hash].js", // 引入文件名的名称
          entryFileNames: "static/js/[name]-[hash].js", // 包的入口文件名称
          assetFileNames: "static/[ext]/[name]-[hash].[ext]", // 资源文件像 字体，图片等
          // 最小化拆分包
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return "invariable";
            }
          },
        },
      },
    },
    // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
    //
    // 1. prevent vite from obscuring rust errors
    clearScreen: false,
    // 2. tauri expects a fixed port, fail if that port is not available
    server: {
      //配置跨域
      proxy: {
        "/tick-basic": {
          // “/api” 以及前置字符串会被替换为真正域名
          target: config.VITE_SERVICE_URL, // 请求域名
          changeOrigin: true, // 是否跨域
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
      port: 1420,
      strictPort: true,
      host: host || false,
      cors: true, // 配置 CORS
      hmr: host
        ? {
            protocol: "ws",
            host,
            port: 1421,
          }
        : undefined,
      watch: {
        // 3. tell vite to ignore watching `src-tauri`
        ignored: ["**/src-tauri/**"],
      },
    },
  };
});
